﻿using Abp.Application.Services;
using Abp.IdentityFramework;
using Abp.Runtime.Session;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using NetCore.Authorization.Users;
using NetCore.Dtos;
using NetCore.Locks;
using NetCore.MultiTenancy;
using System;
using System.Threading.Tasks;

namespace NetCore
{
    /// <summary>
    /// Derive your application services from this class.
    /// </summary>
    public abstract class NetCoreAppServiceBase : ApplicationService
    {
        public TenantManager TenantManager { get; set; }

        public UserManager UserManager { get; set; }
        protected ILock Lock { get; set; }
        protected NetCoreAppServiceBase()
        {
            LocalizationSourceName = NetCoreConsts.LocalizationSourceName;
            Lock = new NullLock();
        }

        #region 默认 获取当前登录用户/租户 检查identityResult认证

        protected virtual async Task<User> GetCurrentUserAsync()
        {
            var user = await UserManager.FindByIdAsync(AbpSession.GetUserId().ToString());
            if (user == null)
            {
                throw new Exception("请登录！");
            }

            return user;
        }

        protected virtual Task<Tenant> GetCurrentTenantAsync()
        {
            return TenantManager.GetByIdAsync(AbpSession.GetTenantId());
        }

        protected virtual void CheckErrors(IdentityResult identityResult)
        {
            identityResult.CheckErrors(LocalizationManager);
        }


        #endregion


        #region 公共Api

        #region JsonResultExtension


        protected JsonResult DJson()
        {
            return DJson("null");
        }

        protected JsonResult DJson(object data)
        {
            return new JsonResult(data);
        }

        protected JsonResult SJson()
        {
            return RJson(true);
        }

        protected JsonResult SJson(object data)
        {
            return new JsonResult(new Message { Status = true, Data = data, Msg = "请求成功" });
        }
        /// <summary>
        /// 返回错误+对象
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        protected JsonResult EJson(object data)
        {
            return new JsonResult(new Message { Status = false, Data = data, Msg = "错误！" });
        }

        /// <summary>
        /// 提供给返回字符串专用
        /// </summary>
        /// <param name="status"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        private JsonResult RJson(bool status, string msg = "成功！")
        {
            return new JsonResult(new Message { Status = status, Msg = msg });
        }

        #endregion

        #endregion

    }
}
